package edu.whu.puppygo.service.Impl;

import com.alibaba.fastjson.JSON;
import edu.whu.puppygo.assistant.HealthAssistant;
import edu.whu.puppygo.config.RabbitmqConfig;
import edu.whu.puppygo.dao.FragmentDao;
import edu.whu.puppygo.dao.PetDao;
import edu.whu.puppygo.dto.EmbeddingDto;
import edu.whu.puppygo.dto.EmbeddingResultDto;
import edu.whu.puppygo.entity.Fragment;
import edu.whu.puppygo.entity.FragmentStatueEnum;
import edu.whu.puppygo.entity.Pet;
import edu.whu.puppygo.entity.User;
import edu.whu.puppygo.service.EmbeddingService;
import edu.whu.puppygo.util.GlobalUser;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author xinjiezhuang
 * @Date 2023-11-30
 * @Description
 **/
@Service
public class EmbeddingServiceImpl implements EmbeddingService {

    @Resource
    RabbitTemplate rabbitTemplate;
    @Resource
    private HealthAssistant healthAssistant;
    @Resource
    private PetDao petDao;
    @Resource
    private FragmentDao fragmentDao;

    @Override
    public boolean sendMsg(String text, Long fragmentId) {
        EmbeddingDto embeddingDto = new EmbeddingDto();
        embeddingDto.setText(text);
        embeddingDto.setFragmentId(fragmentId);

        String jsonBody = JSON.toJSONString(embeddingDto);
        System.out.println("here");
        System.out.println("jsonBody" + jsonBody);
        rabbitTemplate.convertAndSend(RabbitmqConfig.DIRECT_EXCHANGE, "embedding", jsonBody);
        return true;
    }


    @Override
    public void callback(EmbeddingResultDto resultBody) {
        User user = GlobalUser.getUser();
        Long mainPetId = user.getMainPetId();
        Pet pet = petDao.findById(mainPetId).orElseThrow(() -> new RuntimeException("宠物不存在"));
        String answer = resultBody.getAnswer();
        Fragment fragment = fragmentDao.findById(resultBody.getFragmentId()).orElseThrow(() -> new RuntimeException("问答不存在"));
        fragment.setKnowledgeResult(answer);
        fragment.setStatue(FragmentStatueEnum.EMBEDDING_FINISHED);
        fragmentDao.save(fragment);
        //TODO:完整的gpt查询方法
        String diagnose = healthAssistant.getDiagnose(user.getId(), pet.toString(), fragment.getQuestion(), fragment.getImgResult(),fragment.getKnowledgeResult());
        fragment.setAnswer(diagnose);
        //TODO:生成治疗建议

        fragment.setStatue(FragmentStatueEnum.GPT_FINISHED);
        fragmentDao.save(fragment);
    }
}